// pages/homeSearch/homeSearch.js
// 搜索页
var lineHeight = 0;
var endWords = "";
var isNum;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectSwitch: false,
    searchIcon: '/assets/icons/lookup.png',
    delIcon: '/assets/icons/del.png',
    closeIcon: '/assets/icons/close.png',
    screenIcon: '/assets/icons/screen.png',
    addressIcon: '/assets/icons/address.png',
    homeScreenAreaIcon: '/assets/icons/more.png',
    searchHistoryList: [],
    searchResultNavList: [{
        id: 1,
        nav: '综合',
        key: 'zonghe'
      },
      {
        id: 2,
        nav: '最热',
        key: 'zuire'
      },
      {
        id: 3,
        nav: '最新',
        key: 'zuixin'
      }
    ],
    delSearchHistoryIcon: false,
    delIconHidden: true,
    searchResultOpen: false,
    currentNavIndex: 1,
    searchInputValue: '',
    comprehensiveList: [],
    submenu: '',
    labels: ['标签A', '标签B', '标签C', '标签D', '标签E'],
    labelIdx: 0,
    labelVal: '',
    selOptions: [],
    zhezhao: false,
    screenWindow: false,
    areaWindow: false,
    cityName: '',
    currentSexId: null,
    sexList: [{
        id: 0,
        sex: '女',
        isSelected: false
      },
      {
        id: 1,
        sex: '男',
        isSelected: false
      }
    ],
    currentAgeId: null,
    currentPriceId: null,
    minAge: null,
    maxAge: null,
    ageList: [{
        id: 1,
        age: '17岁以下',
        min: 0,
        max: 17,
        isSelected: false
      },
      {
        id: 2,
        age: '18-25岁',
        min: 18,
        max: 25,
        isSelected: false
      },
      {
        id: 3,
        age: '26-30岁',
        min: 26,
        max: 30,
        isSelected: false
      }
    ],
    categoryList: [],
    currentCategoryId: [],
    minPrice: null,
    maxPrice: null,
    priceList: [{
        id: 1,
        price: '100-1000',
        min: 100,
        max: 1000,
        isSelected: false
      },
      {
        id: 2,
        price: '1000-10000',
        min: 1000,
        max: 10000,
        isSelected: false
      },
      {
        id: 3,
        price: '10000-20000',
        min: 10000,
        max: 20000,
        isSelected: false
      }
    ],
    cityData: [],
    cityId: null,
    "hidden": true,
    selectedName: [],
  },
  changeLabel: function(e) {
    // 修改搜索标签
    this.setData({
      labelIdx: e.detail.value,
      labelVal: this.data.labels[e.detail.value]
    })
  },
  clickZhezhao: function() {
    // 点击遮罩层
    this.setData({
      zhezhao: false,
      screenWindow: false,
      areaWindow: false
    })
  },
  clickSelScreen: function() {
    // 打开/关闭筛选弹窗
    this.setData({
      zhezhao: !this.data.zhezhao,
      screenWindow: !this.data.screenWindow
    })
  },
  clickRegion: function() {
    // 打开地区弹窗
    this.setData({
      areaWindow: !this.data.areaWindow,
      cityName: ''
    })
  },
  selectedRegion: function() {
    this.setData({
      areaWindow: !this.data.areaWindow
    })
  },
  clickSexOptions: function(e) {
    // 性别选中项 
    let id = e.currentTarget.dataset.id
    this.setData({
      currentSexId: id,
    })
  },
  clickAgeOptions: function(e) {
    // 适用年龄选中项
    let id = e.currentTarget.dataset.id
    let min = e.currentTarget.dataset.min
    let max = e.currentTarget.dataset.max
    this.setData({
      currentAgeId: id,
      minAge: min,
      maxAge: max,
    })
  },
  clickCategory: function(e) {
    // 类目选中项
    let index = e.currentTarget.dataset.index
    let item = this.data.categoryList[index]
    item.isSelected = !item.isSelected
    let id = e.currentTarget.dataset.id
    let categoryIdArr = this.data.currentCategoryId
    this.setData({
      // 多选控制亮灯
      categoryList: this.data.categoryList
    })
    if (categoryIdArr.indexOf(id) == -1) {
      // 保存选中项id
      categoryIdArr.push(id)
      this.setData({
        currentCategoryId: categoryIdArr
      })
    } else if (categoryIdArr.indexOf(id) > -1) {
      categoryIdArr.splice(categoryIdArr.indexOf(id), 1)
      this.setData({
        currentCategoryId: categoryIdArr
      })
    }
  },
  getCategory: function() {
    // 获取类目
    let _this = this
    let config = wx.getStorageSync('config')
    // 获取大类id判断筛选类目
    wx.getStorage({
      key: 'navid',
      success: function(res) {
        // 加载类目
        wx.request({
          url: config.host + 'api/product/findCategory',
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            type: Number(res.data)
          },
          success(res) {
            if (res.statusCode == 200 && res.data.status == 200) {
              _this.setData({
                categoryList: res.data.data
              })
            }
          }
        })
      },
    })
  },
  clickPrice: function(e) {
    // 案例价格区间选中项
    let id = e.currentTarget.dataset.id
    let min = e.currentTarget.dataset.min
    let max = e.currentTarget.dataset.max
    this.setData({
      currentPriceId: id,
      minPrice: min,
      maxPrice: max
    })
  },
  clickResetBtn: function() {
    // 重置
    let that = this
    this.setData({
      cityName: '',
      currentSexId: null,
      currentAgeId: null,
      minAge: null,
      maxAge: null,
      currentCategoryId: [],
      currentPriceId: null,
      minPrice: null,
      maxPrice: null
    })
    this.data.categoryList.forEach((item, index) => {
      that.setData({
        [`categoryList[${index}].isSelected`]: false
      })
    })
  },
  clickSureBtn: function() {
    let _this = this
    // 确定-发送选中项到服务器,返回搜索结果页，重新加载新数据
    _this.setData({
      searchResultOpen: true
    })
    let sex = _this.data.currentSexId
    let beginAge = _this.data.minAge
    let endAge = _this.data.maxAge
    let categoryIds = _this.data.currentCategoryId
    let lowPrice = _this.data.minPrice
    let highPrice = _this.data.maxPrice
    let cityId = _this.data.cityId
    // 表单数据对应接口：网红1，摄影师2，化妆师3，场地4
    let navid = wx.getStorageSync('navid')
    let type = Number(navid)
    _this.getScreenResult(sex, beginAge, endAge, categoryIds, lowPrice, highPrice, type, cityId)
    // 关闭弹窗
    _this.clickSelScreen()
  },
  selectItem: function(e) {
    // 选择卡片
    let id = String(e.currentTarget.dataset.id)
    let index = e.currentTarget.dataset.index
    let name = e.currentTarget.dataset.name
    let selItemArr = this.data.selOptions
    let selItemName = this.data.selectedName
    if (selItemArr.indexOf(id) == -1) {
      // 原数组没有则新增
      selItemArr.push(id)
    } else if (selItemArr.indexOf(id) > -1) {
      // 原数组包含则删除
      let i = selItemArr.indexOf(id)
      selItemArr.splice(i, 1)
    }
    if (selItemName.indexOf(name) == -1) {
      selItemName.push(name)
    } else if (selItemName.indexOf(name) > -1) {
      let i = selItemName.indexOf(name)
      selItemName.splice(i, 1)
    }
    let string = 'comprehensiveList[' + index + '].isSeled'
    this.setData({
      selOptions: selItemArr,
      selectedName: selItemName,
      [string]: !this.data.comprehensiveList[index].isSeled
    })
  },
  delAllSearchHistory: function() {
    // 删除所有搜索厉害记录
    this.setData({
      searchHistoryList: [],
      delSearchHistoryIcon: false
    })
    wx.removeStorage({
      key: 'searchHistoryList',
      success: function(res) {},
    })
  },
  delInputValueBtn: function() {
    // 删除搜索input内容
    this.setData({
      searchInputValue: '',
      delIconHidden: true
    })
  },
  changeInput: function(e) {
    if (e.detail.value.length > 0) {
      this.setData({
        delIconHidden: false
      })
    } else {
      this.setData({
        delIconHidden: true
      })
    }
    // 数据双向绑定
    let dataset = e.currentTarget.dataset
    let value = e.detail.value
    this.data[dataset.obj] = value.replace(/\s*/g, "")
    this.setData({
      obj: this.data[dataset.obj]
    })
    if (dataset.crt == 'currentAgeId') {
      this.setData({
        currentAgeId: null
      })
    } else if (dataset.crt == 'currentPriceId') {
      this.setData({
        currentPriceId: null
      })
    }
  },
  selectedSearchHistory: function(e) {
    let index = e.currentTarget.dataset.id
    this.setData({
      searchInputValue: this.data.searchHistoryList[index]
    })
  },
  clickSearchBtn: function() {
    // 搜索
    // 保存搜索内容到搜索历史记录
    let _this = this
    let historyArr = this.data.searchHistoryList
    if (this.data.searchInputValue.length > 0) {
      if (historyArr.indexOf(this.data.searchInputValue) < 0) {
        // 判断历史记录是否包含搜索内容，没有则执行保存
        historyArr.unshift(this.data.searchInputValue)
        wx.setStorage({
          key: 'searchHistoryList',
          data: historyArr,
        })
        this.setData({
          searchHistoryList: historyArr,
          searchResultOpen: true
        })
      } else {
        // 有该历史记录则不保存
        this.setData({
          searchResultOpen: true
        })
      }
      // 搜索，显示搜索结果
      let config = wx.getStorageSync('config')
      let url = ''
      let header = {}
      let d = {}
      if (_this.data.selectSwitch) {
        // 选择模式
        url = 'api/label/queryAll'
        header = {
          'content-type': 'application/json;charset=utf-8'
        }
        d = {
          label: _this.data.labels[_this.data.labelIdx],
          searchContent: _this.data.searchInputValue,
          paixu: 1
        }
      } else {
        // 搜索模式
        url = 'api/product/searchContent'
        header = {
          'content-type': 'application/x-www-form-urlencoded'
        }
        d = {
          searchContent: _this.data.searchInputValue,
          paixu: 1
        }
      }
      wx.request({
        url: config.host + url,
        method: 'POST',
        header: header,
        data: d,
        success(res) {
          if (res.statusCode == 200 && res.data.status == 200) {
            let data = []
            res.data.data.forEach(item => {
              item.label = item.label.split(',')
              data.push(item)
            })
            _this.setData({
              comprehensiveList: data
            })
          }
        }
      })

    } else {
      wx.showToast({
        title: '请输入搜索内容！',
        icon: 'none'
      })
    }
  },
  clickScreenNav: function(e) {
    //点击筛选导航
    let _this = this
    let id = e.target.dataset.id
    let submenu = e.target.dataset.key
    let navId = wx.getStorageSync('navid')
    let config = wx.getStorageSync('config')
    this.setData({
      currentNavIndex: id,
      submenu: submenu
    })
    if (_this.data.selectSwitch == false) {
      // 搜索模式
      wx.request({
        url: config.host + 'api/product/searchContent',
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          paixu: id,
          searchContent: _this.data.searchInputValue
        },
        success(res) {
          if (res.data.status == 200 && res.data.msg == 'ok') {
            let data = []
            res.data.data.forEach(item => {
              item.label = item.label.split(',')
              data.push(item)
            })
            _this.setData({
              comprehensiveList: data
            })
          }
        }
      })
    } else if (_this.data.selectSwitch == true) {
      // 选择模式
      wx.request({
        url: config.host + 'api/label/queryAll',
        method: 'POST',
        header: {
          'content-type': 'application/json;charset=utf-8'
        },
        data: {
          label: _this.data.labels[_this.data.labelIdx],
          searchContent: _this.data.searchInputValue,
          paixu: id
        },
        success(res) {
          if (res.data.status == 200) {
            let data = []
            res.data.data.forEach(item => {
              item.label = item.label.split(',')
              data.push(item)
            })
            _this.setData({
              comprehensiveList: data
            })
          }
        }
      })
    }
  },
  clickScreen: function() {
    // 点击筛选
    wx.redirectTo({
      url: '/pages/homeScreen/homeScreen',
    })
  },
  clickHomePage: function(e) {
    // 点击搜索结果进入个人主页
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/homePage/homePage?id=' + id,
    })
  },
  finishSel: function() {
    // 点击确认选择按钮
    let that = this
    let navid = wx.getStorageSync('navid')
    let k = ''
    let kid = ''
    if (navid == '1') {
      k = 'performerNames'
      kid = 'performerIds'
    } else if (navid == '2') {
      k = 'photographerNames'
      kid = 'photographerIds'
    } else if (navid == '3') {
      k = 'dresserNames'
      kid = 'dresserIds'
    } else if (navid == '4') {
      k = 'fieldNames'
      kid = 'fieldIds'
    }
    wx.setStorage({
      key: k,
      data: that.data.selectedName,
    })
    wx.setStorage({
      key: kid,
      data: that.data.selOptions,
    })
    wx.navigateBack({
      delta: 1
    })
  },
  getScreenResult: function(sex, beginAge, endAge, categoryIds, lowPrice, highPrice, type, cityId) {
    // 获取筛选结果
    let that = this
    let config = wx.getStorageSync('config')
    wx.request({
      url: config.host + 'api/product/queryAll',
      method: 'POST',
      data: {
        "sex": sex,
        "beginAge": beginAge,
        "endAge": endAge,
        "categoryIds": categoryIds,
        "lowPrice": lowPrice,
        "highPrice": highPrice,
        "type": type,
        "cityId": cityId
      },
      success(res) {
        if (res.statusCode == 200) {
          let data = []
          res.data.data.forEach(item => {
            item.label = item.label.split(',')
            data.push(item)
          })
          that.setData({
            comprehensiveList: data
          })
        }
      }
    })
  },
  getCityData: function() {
    // 获取城市数据
    let that = this
    let config = wx.getStorageSync('config')
    wx.request({
      url: config.host + 'api/city/city',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        if (res.errMsg == 'request:ok') {
          let list = res.data.data
          let city = {}
          list.forEach(item => {
            city[item.initial] = item.child
          })
          that.setData({
            cityData: city
          })
        } else {
          wx.showToast({
            title: '城市数据获取失败',
            icon: 'none'
          })
        }
      }
    })
  },
  //选择城市，并让选中的值显示在文本框里
  bindCity: function(e) {
    let cityId = e.currentTarget.dataset.cityid;
    let cityName = e.currentTarget.dataset.cityname
    this.setData({
      cityId: cityId,
      cityName: cityName
    })
  },
  //触发全部开始选择
  chStart: function() {
    this.setData({
      trans: ".3",
      hidden: false
    })
  },
  //触发结束选择
  chEnd: function() {
    this.setData({
      trans: "0",
      hidden: true,
      scrollTopId: this.endWords
    })
  },
  // 滑动选择城市
  chMove: function(e) {
    var y = e.touches[0].clientY;
    var offsettop = e.currentTarget.offsetTop;
    var height = 0;
    var that = this;;
    var cityarr = ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"]
    // 获取y轴最大值
    wx.getSystemInfo({
      success: function(res) {
        height = res.windowHeight - 10;
      }
    });
    //判断选择区域,只有在选择区才会生效
    if (y > offsettop && y < height) {
      // console.log((y-offsettop)/lineHeight)
      var num = parseInt((y - offsettop) / lineHeight);
      endWords = cityarr[num];
      // 这里 把endWords 绑定到this 上，是为了手指离开事件获取值
      that.endWords = endWords;
    };
    //去除重复，为了防止每次移动都赋值 ,这里限制值有变化后才会有赋值操作，
    //DOTO 这里暂时还有问题，还是比较卡，待优化
    if (isNum != num) {
      // console.log(isNum);
      isNum = num;
      that.setData({
        showwords: that.endWords
      })
    }
  },
  //获取文字信息
  getWords: function(e) {
    var id = e.target.id;
    this.endWords = id;
    isNum = id;
    this.setData({
      showwords: this.endWords
    })
  },
  //设置文字信息
  setWords: function(e) {
    var id = e.target.id;
    this.setData({
      scrollTopId: id
    })
  },
  labelScreen: function(labelList) {
    // 首页筛选标签数量
    if (labelList.length > 2) {
      if (labelList[0].length > 2 || labelList[1].length > 2) {
        return labelList.slice(0, 2)
      }
    }
    return labelList.slice(0, 3)
  },
  getDataList: function(navId) {
    // 获取页面数据
    let that = this
    let config = wx.getStorageSync('config')
    wx.request({
      url: config.host + 'api/product/queryAll',
      method: 'POST',
      data: {
        type: navId,
        categoryIds: [],
        zonghe: '1'
      },
      success(res) {
        if (res.data.status == 200 && res.data.msg == 'ok') {
          let data = []
          res.data.data.forEach(item => {
            item.label = item.label.split(',')
            item.label = that.labelScreen(item.label)
            data.push(item)
          })
          that.setData({
            comprehensiveList: data
          })
        }
      }
    })
  },
  getLabel: function(type) {
    // 获取标签
    let that = this
    let config = wx.getStorageSync('config')
    wx.request({
      url: config.host + 'api/label/findLabel?type=' + type,
      method: 'GET',
      success(res) {
        if (res.data.status == 200) {
          let labelsData = res.data.data
          labelsData.unshift('默认')
          that.setData({
            labels: labelsData
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('options', options)
    let that = this
    let sex = wx.getStorageSync('sex')
    let beginAge = wx.getStorageSync('beginAge')
    let endAge = wx.getStorageSync('endAge')
    let categoryIds = wx.getStorageSync('categoryIds')
    let lowPrice = wx.getStorageSync('lowPrice')
    let highPrice = wx.getStorageSync('highPrice')
    let cityId = wx.getStorageSync('cityId')
    let cate = options.cate
    let status = options.status
    // 获取标签
    that.getLabel(cate)
    if (status == 'newProject') {
      that.setData({
        selectSwitch: true,
        searchResultOpen: true
      })
      that.getDataList(cate)
      if (cate == 1) {
        wx.setNavigationBarTitle({
          title: '选择网红',
        })
      } else if (cate == 2) {
        wx.setNavigationBarTitle({
          title: '选择摄影师',
        })
      } else if (cate == 3) {
        wx.setNavigationBarTitle({
          title: '选择化妆师',
        })
      } else if (cate == 4) {
        wx.setNavigationBarTitle({
          title: '选择场地',
        })
      }

    }
    if (options.searchResultOpen) {
      // 筛选页有选中项则打开搜索结果
      that.setData({
        searchResultOpen: options.searchResultOpen
      })
    }
    if (!that.data.selectSwitch) {
      // 表单数据对应接口：网红1，摄影师2，化妆师3，场地4
      let navid = wx.getStorageSync('navid')
      let type = Number(navid)
      that.getScreenResult(sex, beginAge, endAge, categoryIds, lowPrice, highPrice, type, cityId)
    }
    // 获取历史搜索记录
    wx.getStorage({
      key: 'searchHistoryList',
      success: function(res) {
        if (res.data.length > 0) {
          that.setData({
            searchHistoryList: res.data
          })
        }
      },
    })
    // 搜索结果默认打开‘综合’nav
    // 获取类目
    that.getCategory()
    // 获取城市数据
    that.getCityData()
  },
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    if (this.data.searchHistoryList.length > 0) {
      this.setData({
        delSearchHistoryIcon: true
      })
    }
    // 调整城市数据渲染
    var cityChild = this.data.cityData;
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        lineHeight = (res.windowHeight - 100) / 22;
        // console.log(res.windowHeight - 100)
        that.setData({
          city: cityChild,
          winHeight: res.windowHeight - 40,
          // winHeight: res.windowHeight - 120,
          lineHeight: lineHeight
        })
      }
    })
  }
})